﻿using System.Collections.Generic;
using com.cruxomatic.configuration.FeatureManager;
using com.cruxomatic.DTOs;
using com.cruxomatic.security;
using com.cruxomatic.views.Administration;
using System.Linq;

namespace com.cruxomatic.controllers.Administration
{
    public class AssignCompaniesToUserController
    {
        readonly IAssignCompanyToUser _view;
        public AssignCompaniesToUserController(IAssignCompanyToUser view)
        {
            _view = view;
        }
         public void InitView(bool IsPostBack)
        {
            if (!IsPostBack)
            {
                
                ICruxSecurityManager securityManager = CruxSecurityManagerFactory.GetSecurityManager();
                _view.AllUsers = securityManager.GetAllUsers();
                _view.AllowedCompanies = securityManager.GetAllCompanies();
                _view.AssignedCompanies = securityManager.GetCompaniesForUser(_view.userid);
                IFeatureManager featureManager = FeatureManagerFactory.GetFeatureManager();
                _view.isSaveAllowed = featureManager.IsFeatureSupported("AllowSaveOnAssignCompanyToUser");
            }
        }

         public void PopulateAssignedCompanies(int userid)
         {
             ICruxSecurityManager securityManager = CruxSecurityManagerFactory.GetSecurityManager();
             _view.AssignedCompanies = securityManager.GetCompaniesForUser(userid);
         }

        public void SaveCompanySettingsForUser()
        {
            //TODO: Provide this method to the security controller.
            ICruxSecurityManager securityManager = CruxSecurityManagerFactory.GetSecurityManager();
            List<CompanyInformation> selectedCompanies = _view.AssignedCompanies;
            UserInformation concernedUser = securityManager.GetUser(_view.userid);

            List<int> selectedCompanyIDs = selectedCompanies.Select(p => p.CompanyID).ToList();
            if (!selectedCompanyIDs.Contains(concernedUser.CompanyID))
                NavigationController.OpenErrorPage("908");
            else
                securityManager.AssignCompaniesToUser(_view.userid, selectedCompanies);

            NavigationController.OpenView("Administration");
        }
    }
}
